import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:http/http.dart' as http;

class WebViewPage extends StatefulWidget {
  var url;
  var title;

  WebViewPage(this.url, this.title);

  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  double _appbarHeight;

  String webTitle;

  @override
  void initState() {
    super.initState();
    if (widget.title == null) {
      _appbarHeight = 0;
    } else {
      _appbarHeight = ScreenUtil.instance.height * 0.036;
    }
    getWebTitle(url: widget.url).then((title) {
      setState(() {
        webTitle = title;
      });
    });
  }

  //获取h5页面标题
  Future<String> getWebTitle({String url}) async {
    var client = http.Client();
    String title;
    client.get(url).then((response) {
      title = RegExp(
              r"<[t|T]{1}[i|I]{1}[t|T]{1}[l|L]{1}[e|E]{1}(\s.*)?>([^<]*)</[t|T]{1}[i|I]{1}[t|T]{1}[l|L   ]{1}[e|E]{1}>")
          .stringMatch(response.body);
      if (title != null) {
        title = title.substring(title.indexOf('>') + 1, title.lastIndexOf("<"));
      } else {
        title = "";
      }
    }).catchError((error) {
      print(error);
    }).whenComplete(
      client.close,
    );
    return title;
  }

  @override
  Widget build(BuildContext context) {
    Widget _title() {
      if (widget.title != null) {
        return Text(widget.title,
            style: TextStyle(color: Colors.white, fontSize: 16.0));
      } else if (webTitle != null) {
        return Text(webTitle,
            style: TextStyle(color: Colors.white, fontSize: 16.0));
      }
      return Container();
    }

    return Scaffold(
      appBar: PreferredSize(
          child: AppBar(
              iconTheme: IconThemeData(color: Colors.white),
              automaticallyImplyLeading: true,
              centerTitle: true,
              title: _title()),
          preferredSize: Size.fromHeight(_appbarHeight)),
      body: WebviewScaffold(
        url: widget.url,
        withZoom: true,
        withLocalStorage: true,
        withJavascript: true,
      ),
    );
  }
}
